package com.nowcoder.community.service;

import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
@Service
public class LikeService {
    @Resource
    private RedisTemplate redisTemplate;
    //点赞---需要添加事务过程

    public void like(int userId, int entityType, int entityId, int entityUserId) {
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
              
                  //不仅要对实体帖子点赞，还要增加发布帖子的人的受赞次数
                  String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                  String userLikeKey=RedisKeyUtil.getUserLikeKey(entityUserId);
                  
                  boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey,userId);
                  
                  //开启事务
                  operations.multi();
                  
                  if (isMember) {
                      operations.opsForSet().remove(entityLikeKey,userId);
                      operations.opsForValue().decrement(userLikeKey);
                  } else {
                      operations.opsForSet().add(entityLikeKey,userId);
                      operations.opsForValue().increment(userLikeKey);
                  }
                  return operations.exec();
            }
        });
    }
    
    public long findEntityLikeCount(int entityType,int entityId){
        String entityLikeKey=RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }
    //查询该帖子实体的被点赞次数
    
    public int findEntityLikeStatus(int userId,int entityType,int entityId){
        String entityLikeKey=RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey,userId)?1:0;
    }
    //查询某用户是否对该帖子实体点了赞
    
    public int findUserLikeCount(int userId) {
        String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
        Integer count =(Integer) redisTemplate.opsForValue().get(userLikeKey);
        return count==null?0:count.intValue();
    }
    //查询某个用户获得的赞数量
}
